# gozerbot/utils/log.py
#
#

""" gozerbots logging module. logging is implemented with the use of a 
    loglevel and a loglist of plugins to log for. 
"""

# basic imports

import logging, logging.handlers, sys, traceback

# the vars
loglevel = 0
logcallbacks = []
loglist = []
logfile = None
enabled = True

def norm(loglevel):
    if loglevel <= 0:
        level = logging.DEBUG
    elif loglevel <= 10:
        level = logging.INFO
    else:
        level = logging.ERROR
    return logging.NOTSET

# basic logger
#logging.basicConfig(level=logging.INFO, format=" [%(asctime)s] (%(name)s) %(message)s")

# add logging to file
#formatter = logging.Formatter(" [%(asctime)s] (%(name)s) %(message)s")
logger = logging.getLogger('gozerapp')

def exceptionmsg():
    """ create a exception traceback as 1 liner. """
    exctype, excvalue, tb = sys.exc_info()
    trace = traceback.extract_tb(tb)
    result = ""   
    for i in trace:
        fname = i[0]
        linenr = i[1]
        func = i[2]
        result += "%s:%s %s | " % (fname, linenr, func)
    del trace
    return "%s%s: %s" % (result, exctype, excvalue)

def rlog(level, descr, txt):
    """ log an item showing description and txt. call logcallbacks if 
        available
    """
    global enabled
    global logger
    #if not enabled:
    #    return
    try:
        #logger = logging.getLogger(descr)
        go = False

        if loglist:

            for item in loglist:

                if item in descr:
                    go = True

        if level >= loglevel or go:
            logger.log(logging.INFO, '(%s) %s' % (descr, txt))

        for cb in logcallbacks:

            try:
                cb(level, descr, txt)
            except:
                print exceptionmsg()

    except (IOError, OSError), ex:
        print str(ex)
        
def disable_logging():
    global enabled
    enabled = False

def enable_logging(level=10, l=[]):
    """ enable logging setting loglevel and/ort loglist """
    global loglevel, loglist, enabled
    #logging.basicConfig(level=logging.INFO, format="[%(asctime)s] %(name)s %(message)s")
    loglevel = int(level)
    loglist = list(l)
    enabled = True
